package com.bpmn.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bpmn.common.exception.ServiceException;
import com.bpmn.system.domain.SysUser;
import com.bpmn.system.domain.form.LoginForm;
import com.bpmn.system.domain.vo.LoginVo;
import com.bpmn.system.domain.vo.UserInfo;
import com.bpmn.system.mapper.SysUserMapper;
import com.bpmn.system.service.AuthService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * @author rain
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private SysUserMapper userMapper;

    @Override
    public LoginVo login(LoginForm form) {
        // 验证应用
        SysUser sysUser = userMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserName, form.getUsername()));
        if (sysUser == null || sysUser.getStatus() == 0) {
            throw new ServiceException("应用不存在或已禁用");
        }
        // 验证用户
        if (!StrUtil.equals(form.getUsername(), sysUser.getUserName())) {
            throw new ServiceException("用户不存在或已禁用");
        }
        // 验证密码
        if (!BCrypt.checkpw(form.getPassword(), sysUser.getPassword())) {
            throw new ServiceException("用户名或密码错误");
        }
        // 生成token
        StpUtil.login(sysUser.getId(), new SaLoginParameter().setExtra("username", sysUser.getUserName()));
        String token = StpUtil.getTokenValue();
        // 返回登录信息
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        UserInfo userInfo = new UserInfo();
        userInfo.setId(sysUser.getId());
        userInfo.setUsername(sysUser.getUserName());
        loginVo.setUser(userInfo);
        return loginVo;
    }

    @Override
    public UserInfo getUserInfo() {
        String tenantId = StpUtil.getLoginIdAsString();
        SysUser sysUser = userMapper.selectById(tenantId);
        UserInfo userInfo = new UserInfo();
        userInfo.setId(sysUser.getId());
        userInfo.setUsername(sysUser.getUserName());
        userInfo.setNickName(sysUser.getNickName());
        return userInfo;
    }

}